package com.example.orchid.paper.task;

import android.content.Context;
import android.text.TextUtils;

import com.example.orchid.paper.PaperApplication;
import com.example.orchid.paper.db.BaseDataSource;
import com.example.orchid.paper.entity.NewsListEntity;
import com.example.orchid.paper.http.HttpClientUtils;

import java.io.IOException;

/**
 * BaseGetNewsTask
 * 从服务器下载内容，base Task
 * Created by Orchid on 2015-10-13.
 */
public abstract class BaseGetNewsTask extends MyAsyncTask<String, String, NewsListEntity> {
    protected Context mContext = null;

    protected ResponseListener mListener = null;

    protected Exception mException = null;

    protected boolean isRefreshSuccess = true;

    protected boolean isContentSame = false;

    public BaseGetNewsTask(Context context, ResponseListener listener) {
        this.mContext = context;
        this.mListener = listener;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        if (mListener != null) {
            mListener.onPreExecute();
        }
    }

    @Override
    protected void onPostExecute(NewsListEntity result) {
        super.onPostExecute(result);

        // 如果当前任务已经取消了，则直接返回
        if (isCancelled()) {
            return;
        }

        if (mListener != null) {
            if (isRefreshSuccess) {
                mListener.onPostExecute(result);
            } else {
                mListener.onFail(mException);
            }
        }
    }

    protected boolean checkIsContentSame(String oldContent, String newContent) {
        return !(TextUtils.isEmpty(oldContent) || TextUtils.isEmpty(newContent))
                && oldContent.equals(newContent);
    }

    protected String getUrl(String url) throws IOException, Exception {
        return HttpClientUtils.get(mContext, url, null);
    }

    protected BaseDataSource getDataSource() {
        return PaperApplication.getDataSource();
    }

    public interface ResponseListener {

        public void onPreExecute();

        public void onPostExecute(NewsListEntity listEntity);

        public void onProgressUpdate(String value);

        public void onFail(Exception e);
    }
}
